package com.pz.minioproxy.controller;

import com.alibaba.fastjson2.JSON;
import com.pz.gulimall.common.utils.R;
import com.pz.minioproxy.service.BigFileUploadService;
import com.pz.minioproxy.service.MinIoService;
import com.pz.minioproxy.service.UploadFileService;
import com.pz.minioproxy.vo.BigFileFeatureReq;
import com.pz.minioproxy.vo.BlobStartRes;
import com.pz.minioproxy.vo.UploadBigFileRes;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.simpleframework.xml.core.Validate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

@RestController
@Slf4j
public class UploadController {
    @Autowired
    private UploadFileService uploadFileService;
    @Autowired
    private BigFileUploadService bigFileUploadService;
    @Autowired
    private MinIoService minIoService;

    /**
     * @return {data: {bucket},{objectName}}
     */
    @PostMapping("/upload-file")
    public R uploadSingleFile(@RequestParam(value = "file") MultipartFile file){
        if(file.isEmpty()){
            log.error("uploadSingleFile --- fail");
            return R.error("empty file");
        }
        //object {bucket},{objectName}
        String object = uploadFileService.uploadFile(file);

        return R.okData(object);
    }

    /**
     * 上传大文件的第一步，获取要上传大文件的起始分块
     * @return {data: {大文件分块列表的起始上传index}}
     */
    @PostMapping("/upload-bigfile/getStartIndex")
    public R getStartBlob(@RequestBody @Valid BigFileFeatureReq feature){
        BlobStartRes ans = bigFileUploadService.getStartBlobIndex(feature);

        return R.okData(ans);
    }

    /**
     * 上传大文件的分块
     * @param feature 大文件基本信息(绝对不能添加@RequestBody)
     * @return  {data: {bucket},{objectName}}
     */
    @PostMapping("/upload-bigfile/blob")
    public R uploadBigFileBlob(@Valid BigFileFeatureReq feature){
        if(feature.getBlob() == null || feature.getBlob().isEmpty()){
            log.error("upload blob file --- fail");
            return R.error("empty blob file");
        }
        UploadBigFileRes ans = bigFileUploadService.uploadBigFile(feature.getBlob(), feature);
        return R.okData(ans);
    }

    @GetMapping("/get-link")
    public R getLink(@RequestParam("bucket") String bucket, @RequestParam("objectName") String objectName){
        String link = minIoService.getObjectUrl(bucket, objectName);
        return R.ok().put("data", link);
    }
}
